import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';

///
/// Created by hai046 on 2022/12/9
///
class FirebaseCrashlyticsUtils {
  static final FirebaseCrashlyticsUtils _instance =
      FirebaseCrashlyticsUtils._();

  factory FirebaseCrashlyticsUtils() => _instance;
  FirebaseCrashlytics? _firebaseCrashlytics;

  FirebaseCrashlyticsUtils._() {
    _firebaseCrashlytics = FirebaseCrashlytics.instance;
  }

  ///[msg] 打印一下对应消息
  ///记录包含在下一个致命或非致命报告中的消息。
  ///日志在Firebase Crashlytics控制台的会话视图中可见。
  ///换行符被删除，超长消息被截断。
  ///最大日志大小为64k。如果超过，日志将滚动，以便从最早的消息开始删除消息。
  void log(String msg) {
    _firebaseCrashlytics?.log(msg);
  }

  void setUserIdentifier(String identifier) {
    _firebaseCrashlytics?.setUserIdentifier(identifier);
  }

  void setCustomKey(String key, Object value) {
    _firebaseCrashlytics?.setCustomKey(key, value);
  }

  void recordFlutterError(FlutterErrorDetails flutterErrorDetails,
      {bool fatal = false}) {
    if (flutterErrorDetails.exception is! StateError) {
      //主要是网络或图片异常，直接先过滤吧
      _toastWarn();
    }
    _firebaseCrashlytics?.recordFlutterError(flutterErrorDetails, fatal: fatal);
  }

  void recordError(dynamic exception, StackTrace? stack,
      {dynamic reason,
      Iterable<Object> information = const [],
      bool? printDetails,
      bool fatal = false}) {
    _toastWarn();
    _firebaseCrashlytics?.recordError(exception, stack,
        reason: reason,
        information: information,
        printDetails: printDetails,
        fatal: fatal);
  }

  void _toastWarn() async {
    if (!kReleaseMode) {
      var tag = 'error_dialog';
      // SmartDialog.dismiss(tag: tag);
      // SmartDialog.show(
      //     builder: (context) {
      //       return Container(
      //         padding: EdgeInsets.all(20),
      //         decoration: BoxDecoration(
      //           borderRadius: BorderRadius.circular(5),
      //           color: Theme.of(context).colorScheme.surface,
      //         ),
      //         child: Text(
      //           'Warn\n'
      //           '⚠️有异常日志，请开发检查日志进行排查！\n'
      //           '⚠️有异常日志，请开发检查日志进行排查！\n'
      //           '⚠️有异常日志，请开发检查日志进行排查！',
      //           textAlign: TextAlign.center,
      //           style: TextStyle(color: Colors.red),
      //         ),
      //       );
      //     },
      //     tag: tag,
      //     keepSingle: true);
    }
  }
}
